/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package model;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import org.jaxen.jdom.JDOMXPath;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

/**
 *
 * @author thedaego
 */
public class PriceScraper
{
    private DataLocator dataLocator;

    public PriceScraper(DataLocator dataLocator) {
        this.dataLocator = dataLocator;
    }

    public String getPrice() throws ScraperException 
    {
        String price = null;
        try {
            HttpURLConnection conn = (HttpURLConnection) dataLocator.getLocatorUrl().openConnection();
            //set the user agent in order to bypas 403 errors
            conn.addRequestProperty("User-Agent", "Mozilla/5.0 "
                    + "(Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) "
                    + "Gecko/20061204 Firefox/2.0.0.1");
            // build a JDOM tree from a SAX stream provided by tagsoup
            SAXBuilder builder = new SAXBuilder("org.ccil.cowan.tagsoup.Parser");
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            Document doc;
  

            doc = builder.build(reader);

            JDOMXPath pricePath = new JDOMXPath(dataLocator.getXpath());
            pricePath.addNamespace("h","http://www.w3.org/1999/xhtml");
 
            price = ((Element)pricePath.selectSingleNode(doc)).getText();

        } catch (Exception ex) {
            throw new ScraperException("Error retrieving price from: "
                    + dataLocator.getLocatorUrl()
                    + "\n" +ex.getMessage(), ex);
        }

        return price;
    }

}
